package main.leetcode.offer.firstround.from51to68;

/**
 * 53-I.在排序数组中查找数字
 *
 * <p>统计一个数字在排序数组中出现的次数。
 *
 * <p>
 *
 * <p>示例 1:输入: nums = [5,7,7,8,8,10], target = 8 输出: 2
 *
 * <p>示例 2:输入: nums = [5,7,7,8,8,10], target = 6 输出: 0
 *
 * <p>限制：0 <= 数组长度 <= 50000
 *
 * <p>来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/zai-pai-xu-shu-zu-zhong-cha-zhao-shu-zi-lcof
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 */
public class ex53I {
    public static void main(String[] args) {
        //        System.out.println(binarySearch(new int[] {1, 2, 2, 3, 3, 3, 3, 33, 444}, 0));
        System.out.println(new ex53I().search(new int[] {5, 7, 7, 8, 8, 10}, 6));
    }

    // 利用api
    //    public int search(int[] nums, int target) {
    //        int n = nums.length;
    //        if (n < 1) return 0;
    //        int index = binarySearch(nums, target);
    //        if (index < 0) return 0;
    //        int i = index;
    //        int res = 1;
    //        while (i > 0 && nums[--i] == target) res++;
    //        i = index;
    //        while (i < n - 1 && nums[++i] == target) res++;
    //        return res;
    //    }

    // 自己写二分
    public int search(int[] nums, int target) {
        int lo = 0, hi = nums.length - 1;
        int mid;
        int res = 0;
        while (lo <= hi) {
            mid = lo + (hi - lo) / 2;
            if (nums[mid] < target) lo = mid + 1;
            else if (nums[mid] > target) hi = mid - 1;
            else {
                for (int i = mid; i > -1 && nums[i] == target; res++, i--) ;
                for (int i = mid + 1; i < nums.length && nums[i] == target; res++, i++) ;
                break;
            }
        }
        return res;
    }
}
